package cn.big.bigd.configure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import cn.big.bigd.ybp.service.YbpUserService;

/**
 * 
 * @author wangfan
 *
 */

@Configuration
@EnableWebSecurity
public class SecurityConfigure extends WebSecurityConfigurerAdapter{


    @Autowired
    YbpUserService userService ;

    @Bean
    PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    	//指定密码加密所使用的加密器为passwordEncoder()
        auth.userDetailsService(userService).passwordEncoder(getPasswordEncoder())
                .and();
      //不删除凭据，以便记住用户
      		auth.eraseCredentials(false);

     
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();
        http.authorizeRequests()
                .antMatchers("/admin/super/**").hasAuthority("SUPERADMIN")
                .antMatchers("/admin/**").hasAnyAuthority("ADMIN","SUPERADMIN")
                .antMatchers("/ybp/**").hasAnyAuthority("ADMIN","USER","SUPERADMIN")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                //指定登录页
                .loginPage("/login")
                .defaultSuccessUrl("/ybp/success-login")
                .permitAll()
                .and().csrf().disable();
        http.logout().logoutSuccessUrl("/").invalidateHttpSession(true).deleteCookies();
    }

}
